package cn.iocoder.yudao.module.cmt.service.service;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.service.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.service.ServiceCategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.service.ServiceCategoryMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ServiceCategoryServiceImpl implements ServiceCategoryService {

    @Resource
    private ServiceCategoryMapper serviceCategoryMapper;

    @Override
    public Long createServiceCategory(ServiceCategorySaveReqVO createReqVO) {
        ServiceCategoryDO serviceCategory = BeanUtils.toBean(createReqVO, ServiceCategoryDO.class);
        serviceCategoryMapper.insert(serviceCategory);
        return serviceCategory.getId();
    }

    @Override
    public void updateServiceCategory(ServiceCategorySaveReqVO updateReqVO) {
        validateServiceCategoryExists(updateReqVO.getId());
        ServiceCategoryDO updateObj = BeanUtils.toBean(updateReqVO, ServiceCategoryDO.class);
        serviceCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteServiceCategory(Long id) {
        validateServiceCategoryExists(id);
        serviceCategoryMapper.deleteById(id);
    }

    private void validateServiceCategoryExists(Long id) {
        if (serviceCategoryMapper.selectById(id) == null) {
            throw exception(SERVICE_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public ServiceCategoryDO getServiceCategory(Long id) {
        return serviceCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<ServiceCategoryDO> getServiceCategoryPage(ServiceCategoryPageReqVO pageReqVO) {
        return serviceCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteServiceCategoryListByIds(List<Long> ids) {
        ids.forEach(this::validateServiceCategoryExists);
        serviceCategoryMapper.deleteBatchIds(ids);
    }

}
